package xin.alum.aim.util;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import lombok.SneakyThrows;

public class ProtoDeserializer extends StdScalarDeserializer {

    public ProtoDeserializer() {
        super(com.google.protobuf.GeneratedMessageV3.class);
    }

    @Override
    @SneakyThrows
    public Object deserialize(JsonParser p, DeserializationContext gtxt) {
        //判断是否“[”开头 是的话跳过“[”，结束时也要跳过“]”
        boolean b = p.currentToken() == JsonToken.START_ARRAY;
        if (b) {
            p.nextToken();
        }
        String text = p.getText();
        Class<?> aClass = Class.forName(text);
        p.nextToken();
        Object parseFrom = aClass.getMethod("parseFrom", byte[].class).invoke(null, p.getBinaryValue());
        if (b) {
            p.nextToken();
        }
        return parseFrom;
    }
}